# coding=UTF-8

import os
import sys
import traceback
import maya

import maya.cmds as cmds
import maya.OpenMaya as om
try:
    import JTK
except:
    sys.path.append(r'T:/CGRepository/CGCodeRepos/JTKCG')
    sys.path.append(r'T:/CGRepository/CGCodeRepos/pyLibs/python3')

    import JTK

from JTK import jcore

log_name = 'JTKMayaPipline'
log = jcore.jtk_log(logger_name=log_name)

log.info("%s Initializing..." % log_name)

try:
    JTK_Path = os.environ['JTK_PATH']
    JTK_Launcher = os.environ['JTK_LC']
    JTK_Launcher_name = os.environ['JTK_LCN']
    log.info(u"JTK Setup : %s -> %s -> %s" % (JTK_Path, JTK_Launcher, JTK_Launcher_name))
except Exception:
    log.info("WithOut JTK Setup...")
    log.warning(traceback.format_exc())

try:
    log.info("Shelf install...")
    from _shelf.auto_shelf import auto_shelf

    cmds.evalDeferred("auto_shelf()")
except Exception:
    log.info("WithOut Shelf Setup...")
    log.warning(traceback.format_exc())

log.info("Execute init script...")
import _initScript

try:
    import pymel.core as pm
except Exception:
    log.warning("can not import pymel:\n %s" % traceback.format_exc())


# setup open bookmarks
def remove_op_books(_):
    bookmark = cmds.optionVar(q=("CustomFileDialogSidebarUrls"))
    min = os.environ['OPEN_BOOKS_MIN']
    max = len(bookmark)
    remove_num_list = []
    for i in range(int(min), max, 1):
        remove_num_list.append(i)
    remove_num_list = sorted(remove_num_list, reverse=True)
    for i in remove_num_list:
        cmds.optionVar(rfa=("CustomFileDialogSidebarUrls", i))


if 'OPEN_BOOKS' in os.environ:
    bookmark = cmds.optionVar(q=("CustomFileDialogSidebarUrls"))
    os.environ['OPEN_BOOKS_MIN'] = str(len(bookmark))
    for p in os.environ['OPEN_BOOKS'].split(';'):
        cmds.optionVar(sva=('CustomFileDialogSidebarUrls', p))

    om.MEventMessage.addEventCallback('quitApplication', remove_op_books)

log.info("%s Initialized.\n\n\n" % log_name)
